package com.lagou.mvcframework.servlet;

import com.lagou.mvcframework.annotations.*;
import com.lagou.mvcframework.pojo.Handler;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LgDispatcherServlet extends HttpServlet {

    // 解析配置文件
    private Properties properties = new Properties();
    // 缓存扫描到的类的全限定类名
    private List<String> classNames = new ArrayList<>();
    // ioc容器
    private Map<String, Object> ioc = new HashMap<>();
    // handlerMapping
//    private Map<String, Method> handlerMapping = new HashMap<>(); // 存储url和Method之间的映射关系
    private List<Handler> handlerMapping = new ArrayList<>();

    private Map<Pattern, String[]> securityMapping = new HashMap<>();

    @Override
    public void init(ServletConfig config) throws ServletException {
        // 1 加载配置文件 springmvc.properties
        String contextConfigLocation = config.getInitParameter("contextConfigLocation");
        doLoadConfig(contextConfigLocation);

        // 2 扫描相关的类，扫描注解
        doScan(properties.getProperty("scanPackage"));


        // 3 初始化bean对象（实现ioc容器，基于注解）
        doInstance();

        // 4 实现依赖注入
        doAutoWired();

        // 5 构造一个HandlerMapping处理器映射器，将配置好的url和Method建立映射关系
        initHandlerMapping();

        System.out.println("lagou mvc 初始化完成....");

        // 等待请求进入，处理请求
    }

    // 构造一个HandlerMapping处理器映射器，将配置好的的url和Method建立映射关系，重要
    private void initHandlerMapping() {
        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            Object object = entry.getValue();
            Class<?> aClass = object.getClass();
            if (!aClass.isAnnotationPresent(QjcController.class)) continue;
            if (!aClass.isAnnotationPresent(QjcRequestMapping.class)) continue;
            QjcRequestMapping qjcRequestMapping = aClass.getAnnotation(QjcRequestMapping.class);
            String baseUrl = qjcRequestMapping.value();
            Method[] methods = aClass.getMethods();
            for (Method method : methods) {
                if (!method.isAnnotationPresent(QjcRequestMapping.class)) continue;
                QjcRequestMapping qjcRequestMappingMethod = method.getAnnotation(QjcRequestMapping.class);
                String methodUrl = qjcRequestMappingMethod.value();
                String url = baseUrl + methodUrl;
                Pattern pattern = Pattern.compile(url);

                if (method.isAnnotationPresent(QjcSecurity.class)) {
                    QjcSecurity annotation = method.getAnnotation(QjcSecurity.class);
                    String[] value = annotation.value();
                    securityMapping.put(pattern, value);
                }

//                handlerMapping.put(url, method); // 主要改造
                Handler handler = new Handler(object, method, pattern);
                Parameter[] parameters = method.getParameters();
                for (int i = 0; i < parameters.length; i++) {
                    Parameter parameter = parameters[i];
                    if (parameter.getType() == HttpServletRequest.class || parameter.getType() == HttpServletResponse.class) {
                        // 如果是request和response对象，那么参数名称写HttpServletRequest和HttpServletResponse
                        handler.getParamIndexMapping().put(parameter.getType().getSimpleName(), i);
                    } else {
                        handler.getParamIndexMapping().put(parameter.getName(), i);
                    }
                }
                handlerMapping.add(handler);
            }
        }
    }

    // 进行依赖注入
    private void doAutoWired() {
        if (ioc.isEmpty()) return;
        // 比那里ioc容器中的所有实例化对象，然后遍历其属性是否使用了QjcAutowired注解，是的话就进行依赖注入
        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            Object object = entry.getValue();
            Field[] declaredFields = object.getClass().getDeclaredFields();
            for (Field field : declaredFields) {
                if (!field.isAnnotationPresent(QjcAutowired.class)) continue;

                QjcAutowired annotation = field.getAnnotation(QjcAutowired.class);
                String beanName = annotation.value(); //需要注入的bean的id
                if (StringUtils.isBlank(beanName)) {
                    // 如果注解中没有添加bean的id，则直接使用接口名
                    beanName = field.getType().getName();
                }
                // 开启赋值
                field.setAccessible(true);
                try {
                    // 将该属性设置进去
                    field.set(object, ioc.get(beanName));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    // 初始化bean对象放入IOC容器
    // 基于classNames缓存的类的全限定类名，以及反射技术，完成对象的创建和管理
    private void doInstance() {
        if (classNames.size() == 0) return;
        try {
            for (String className : classNames) {
                // 反射获取class
                Class<?> aClass = Class.forName(className);
                // 区分controller、service
                if (aClass.isAnnotationPresent(QjcController.class)) {
                    QjcController annotation = aClass.getAnnotation(QjcController.class);
                    String beanName = annotation.value();
                    if (StringUtils.isBlank(beanName)) {
                        String simpleName = aClass.getSimpleName();
                        beanName = lowerFirst(simpleName);
                    }
                    Object o = aClass.newInstance();
                    ioc.put(beanName, o);
                } else if (aClass.isAnnotationPresent(QjcService.class)) {
                    QjcService annotation = aClass.getAnnotation(QjcService.class);
                    String beanName = annotation.value();
                    if (StringUtils.isBlank(beanName)) {
                        String simpleName = aClass.getSimpleName();
                        beanName = lowerFirst(simpleName);
                    }
                    Object o = aClass.newInstance();
                    ioc.put(beanName, o);

                    // service层往往是有接口的，面向接口开发，此时再以接口名为id，放入一份对象到ioc中，便于后期根据接口类型注入
                    Class<?>[] interfaces = aClass.getInterfaces();
                    for (Class<?> anInterface : interfaces) {
                        ioc.put(anInterface.getName(), aClass.newInstance());
                    }
                } else {
                    continue;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 首字母小写
    private String lowerFirst(String simpleName) {
        char[] chars = simpleName.toCharArray();
        if ('A' <= chars[0] && 'Z' >= chars[0]) {
            chars[0] += 32;
        }
        return String.valueOf(chars);
    }

    // 扫描相关的类
    // scanPackage: com.lagou.demo  package---->  磁盘上的文件夹（File）  com/lagou/demo
    private void doScan(String scanPackage) {
        // 获取磁盘路径
        String scanPackagePath = Thread.currentThread().getContextClassLoader().getResource("").getPath() + scanPackage.replace(".", "/");
        File pack = new File(scanPackagePath);
        File[] files = pack.listFiles();
        for (File file : files) {
            if (file.isDirectory()) { // 子package
                // 递归
                doScan(scanPackage + "." + file.getName());
            } else if (file.getName().endsWith("class")) {
                // 保存全限定类名
                String className = scanPackage + "." + file.getName().replace(".class", "");
                classNames.add(className);
            }
        }
    }

    // 加载配置文件
    private void doLoadConfig(String contextConfigLocation) {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);

        try {
            properties.load(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       /* // 处理请求，根据url，找到对应的Method方法，进行调用
        // 获取uri
        String requestURI = req.getRequestURI();
        Method method = handlerMapping.get(requestURI);
        // invoke(Object obj, Object... args) 此处无法完成调用，没有对象，也没有参数，需要改造一下HandlerMapping
        method.invoke();*/

        String username = req.getParameter("name");
        String requestURI = req.getRequestURI();

        // 通过uri处理能够处理当前请求的handler
        Handler handler = getHandler(req);
        if (handler == null) {
            resp.getWriter().write("404 not found");
            return;
        }

        // 解析@QjcSecurity注解
        Method method = handler.getMethod();
        if (method.isAnnotationPresent(QjcSecurity.class)) {
            QjcSecurity annotation = method.getAnnotation(QjcSecurity.class);
            String[] values = annotation.value();
            for (Pattern pattern : securityMapping.keySet()) {
                Matcher matcher = pattern.matcher(requestURI);
                if (matcher.matches()) {
                    if (!Arrays.asList(values).contains(username)) {
                        resp.getWriter().write("Sorry! No permission.");
                        return;
                    } else {
                        break;
                    }
                }
            }
        }


        // 获取所有参数类型
        Class<?>[] parameterTypes = method.getParameterTypes();

        // 创建一个参数数组（是要传入反射调用的）
        Object[] paramValues = new Object[parameterTypes.length];
        // 向参数数组中塞值，并且要和方法的形参位置一样
        Map<String, String[]> parameterMap = req.getParameterMap();
        // 遍历request中所有参数，填充除了request,response之外的参数
        for (Map.Entry<String, String[]> param : parameterMap.entrySet()) {
            // name=1&name=2   name [1,2]
            String value = StringUtils.join(param.getValue(), ",");// 如同 1,2
            if (!handler.getParamIndexMapping().containsKey(param.getKey())) continue;
            // 如果参数和方法中的参数匹配上了，填充数据
            // 方法形参确实有该参数，找到它的索引位置，对应的把参数值放入paraValues
            Integer index = handler.getParamIndexMapping().get(param.getKey());

            paramValues[index] = value; // 把前台传递过来的参数值填充到对应的位置去
        }
        Integer reqIndex = handler.getParamIndexMapping().get(HttpServletRequest.class.getSimpleName());
        paramValues[reqIndex] = req;

        Integer respIndex = handler.getParamIndexMapping().get(HttpServletResponse.class.getSimpleName());
        paramValues[respIndex] = resp;

        try {
            method.invoke(handler.getController(), paramValues);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    private Handler getHandler(HttpServletRequest req) {
        String requestURI = req.getRequestURI();
        for (Handler handler : handlerMapping) {
            Matcher matcher = handler.getPattern().matcher(requestURI);
            if (!matcher.matches()) continue;
            return handler;
        }
        return null;
    }
}
